package cn.com.hatech.blog.module.admin.attach.service.impl;

import cn.com.hatech.blog.common.constant.LogActions;
import cn.com.hatech.blog.common.constant.Types;
import cn.com.hatech.blog.common.constant.WebConst;
import cn.com.hatech.blog.common.exception.TipException;
import cn.com.hatech.blog.common.utils.TaleUtils;
import cn.com.hatech.blog.common.utils.UserRequest;
import cn.com.hatech.blog.module.admin.attach.entity.Attach;
import cn.com.hatech.blog.module.admin.attach.mapper.AttachMapper;
import cn.com.hatech.blog.module.admin.attach.service.IAttachService;
import cn.com.hatech.blog.module.admin.dashboard.service.ILogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.service.impl
 * @className: AttachServiceImpl
 * @author: xuruikai
 * @description: 附件管理业务层接口实现
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Service
@Slf4j
public class AttachServiceImpl implements IAttachService {

    public static final String CLASSPATH = TaleUtils.getUploadFilePath();

    @Autowired
    private ILogService logService;

    @Resource
    private AttachMapper attachMapper;

    @Override
    public IPage<Attach> getAttaches(Integer page, Integer limit) {
        QueryWrapper<Attach> attachQueryWrapper = new QueryWrapper<>();
        attachQueryWrapper.orderByDesc("create_time");
        return attachMapper.selectPage(new Page<>(page, limit), attachQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(String id) {
        Attach attach = this.attachMapper.selectById(id);
        if (null == attach) {
            throw new TipException("不存在该附件");
        }
        attachMapper.deleteById(id);
        new File(CLASSPATH + attach.getFilePath()).delete();
        return logService.insertLog(LogActions.DEL_ARTICLE.getAction(), attach.getFilePath(), UserRequest.getRemoteAddr(), UserRequest.getCurrentUserId());
    }

    @Override
    public List<String> uploadFile(MultipartFile[] multipartFiles) {
        List<String> errorFiles = new ArrayList<>();
        try {
            for (MultipartFile multipartFile : multipartFiles) {
                String fileName = multipartFile.getOriginalFilename();
                if (multipartFile.getSize() <= WebConst.MAX_FILE_SIZE) {
                    String fileKey = TaleUtils.getFileKey(fileName);
                    String fileType = TaleUtils.isImage(multipartFile.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType();
                    File file = new File(CLASSPATH + fileKey);
                    try {
                        FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Attach attach = Attach.builder()
                            .fileName(fileName)
                            .authorId(UserRequest.getCurrentUserId())
                            .filePath(fileKey)
                            .fileType(fileType)
                            .createTime(new Date())
                            .build();
                    attachMapper.insert(attach);
                } else {
                    errorFiles.add(fileName);
                }
            }
        } catch (Exception e) {
            log.error("{}", e.getMessage());
            throw new TipException("服务器异常,文件上传失败");
        }
        return errorFiles;
    }
}
